<style lang="less">
  @import '../styles/common.less';
  @import '../tables/components/table.less';
</style>
<style>

</style>
<template>
  <div class="journal-div">
    <Row :gutter="10" v-if="showReview == false">
      <Card>
        <div class="table-head">
          <Button type="primary" class="Button" @click="reportUserFun()">设置默认上报人</Button>
          <Button type="primary" class="Button" @click="ExportData()">导出数据</Button>
          <Button type="primary" class="Button" @click="remove()">删除</Button>
          <Button type="primary" class="Button" @click="add()">添加</Button>
          <Button type="primary" class="Button" @click="review()" v-if="leadership == true">检阅</Button>
        </div>
        <Row class="margin-top-10">
          <Table stripe border :columns="columns" :data="data" @on-row-click="onRowData"
                 @on-selection-change="selectionChange"></Table>
        </Row>
        <div style="margin: 10px;overflow: hidden;height: 36px;">
          <div style="float: right;">
            <Page :total="total" :current="page" @on-change="changePage" show-elevator></Page>
          </div>
        </div>
      </Card>
    </Row>
    <Row class="row" v-show="showReview != false">
      <Col span="10" class="padding-left-10 list-div">
      <Card>
        <div class="DatePicker-div">
          <DatePicker
              :open="true"
              v-model="DatePickerValue"
              type="date"
              @on-change="handleChange">
            <a href="javascript:void(0)" @click="">
              <template v-if="DatePickerValue === ''"></template>
            </a>
          </DatePicker>
        </div>
      </Card>
      </Col>
      <Col span="14" class="padding-left-10 list-div">
      <Card class="padding-10">
        <div class="table-head">
          <span>{{Datetime}}</span>
          <Button type="primary" class="Button" @click="review_back()">返回</Button>
        </div>
        <Row class="margin-top-10">
          <Table stripe border :columns="columns_review" :data="data_review" @on-row-click="onRowData_review"></Table>
        </Row>
      </Card>
      </Col>
    </Row>

    <!--详情-->
    <Drawer :closable="false" :width="DrawerWidth" v-model="showCurrentTableData" class="Drawer-body">
      <div class="Drawer_pStyle">
        <span></span>
        <span class="del" @click="asyncOK"><Icon type="md-close"/></span>
      </div>
      <div class="body">
        <Form label-position="top">
          <FormItem label="姓名">
            <div class="dataDetail-div" v-text="dataDetail.name"></div>
          </FormItem>
          <FormItem label="头像" v-if="dataDetail.avatar && dataDetail.avatar.url">
            <div class="head-dataDetail-div">
              <img :src="dataDetail.avatar.url" class="img">
            </div>
          </FormItem>
          <FormItem label="创建时间" v-if="dataDetail.create_time">
            <div class="dataDetail-div" v-text="dataDetail.create_time"></div>
          </FormItem>
          <FormItem label="最后修改时间" v-if="dataDetail.last_modify_time">
            <div class="dataDetail-div" v-text="dataDetail.last_modify_time"></div>
          </FormItem>
          <FormItem label="内容" v-if="dataDetail.content">
            <div class="dataDetail-div ck-editor-content" v-html="dataDetail.content"></div>
          </FormItem>
        </Form>
      </div>
      <div class="footer" :style="{width: DrawerWidth - 32 + 'px'}">

      </div>
    </Drawer>
    <!--编辑-->
    <Drawer :closable="false" :width="WindowWidth" v-model="addCurrentTableData" class="Drawer-body">
      <div class="Drawer_pStyle">
        <span>编辑</span>
        <span class="del" @click="hideAddModal"><Icon type="md-close"/></span>
      </div>
      <div class="body">
        <table class="add-table" border="0" cellpadding="0" cellspacing="0">
          <tr>
            <td class="left paddingTop22" valign="top" align="right">
              <Form label-position="top" class="from-content">
                <FormItem label="">
                  <!--<textarea name="content" id="content"></textarea>-->
                  <div id="content" class="ck-editor-content" :style="{minHeight: WindowHeight - 200 + 'px'}"></div>
                  <!--<div id="toolbar-container"></div>
                  <div id="editor" class="editor-content"></div>-->
                </FormItem>
              </Form>
            </td>
            <td class="right" valign="top" :style="{width: WindowWidth > 1440 ? WindowWidth*0.3 + 'px' : '288px'}">
              <Form label-position="top">
                <FormItem label="上报人">
                  <div class="dataDetail-div">
                    <Tree ref="add_report_user" :data="TreeData" show-checkbox multiple></Tree>
                  </div>
                </FormItem>
              </Form>
            </td>
          </tr>
        </table>
      </div>
      <div class="footer" :style="{width: WindowWidth - 32 + 'px'}">
        <Button type="text" @click="hideAddModal">取消</Button>
        <Button type="primary" :loading="saveLoading" @click="save()">确定</Button>
      </div>
    </Drawer>
    <!--默认上报人-->
    <Drawer :closable="false" :width="DrawerWidth" v-model="reportUser" class="Drawer-body">
      <p class="Drawer_pStyle">设置默认上报人</p>
      <div class="body">
        <Form label-position="top">
          <FormItem label="上报人">
            <div class="dataDetail-div">
              <Tree ref="report_user" :data="TreeData" show-checkbox multiple></Tree>
            </div>
          </FormItem>
        </Form>
      </div>
      <div class="footer" :style="{width: DrawerWidth - 32 + 'px'}">
        <Button type="text" @click="hidereportUser">取消</Button>
        <Button type="info" :loading="saveLoading" @click="savereportUser">保存</Button>
      </div>
    </Drawer>
  </div>
</template>

<script>
  import Cookies from 'js-cookie';
  import Util from '../../libs/util';
  import Utils from '../../libs/mod.utils';
  import String from '../../libs/mod.string';
  import Modal from '../../libs/mod.Modal';
  import Ckeditor from '../../libs/mod.ckeditor';
  export default {
    components: {},
    data () {
      return {
        total: 0,
        page: 1,
        size: 10,
        id: '',
        searchConName: '',
        searchConTel: '',
        showReview: false,
        vueEventCalendar: false,
        showCurrentTableData: false,
        loading: true,
        showCurrentColumns: [],
        editInlineAndCellData: [],
        columns: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            key: 'name',
            title: '姓名',
          },
          {
            key: 'create_time',
            title: '创建时间',
          },
          {
            key: 'last_modify_time',
            title: '最后修改时间',
          },
          {
            title: 'Action',
            key: 'action',
            width: 150,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: e => {
                      e.stopPropagation();
                      var data = params.row;
                      this.update(data, params.index);
                    }
                  }
                }, '修改')
              ]);
            }
          }
        ],
        data: [],
        dataDetail: {},
        initTable: [],
        addCurrentTableData: false,
        saveLoading: false,
        ajaxType: 'add',
        addData: {
          content: '',
        },
        selectionArr: [],
        editor: null,
        comePageTime: 0,// 进入页面的时间戳
        from: '',
        to: '',
        ReviewData: {},
        data_review: [],
        demoEvents: [],
        columns_review: [
          {
            key: 'name',
            title: '姓名',
          },
          {
            key: 'create_time',
            title: '创建时间',
          },
          {
            key: 'last_modify_time',
            title: '最后修改时间',
          },
        ],
        Datetime: '',
        leadership: false,
        DrawerWidth: Util.constant.DrawerWidth,// 抽屉的宽度
        WindowWidth: Util.constant.WindowWidth,// 窗口的宽度
        WindowHeight: Util.constant.WindowHeight,// 窗口的高度
        reportUser: false,
        TreeData: [],
        checked_dep_arr: [],
        checked_users_arr: [],
        DatePickerValue: '',
      };
    },
    beforeMount: function () {
      var _this = this;
      var comePageTime = _this.comePageTime;
      var timestamp = new Date().getTime();
      _this.comePageTime = timestamp;
    },
    beforeDestroy: function () {
      var _this = this;
      var comePageTime = _this.comePageTime;
      var timestamp = new Date().getTime();
      var type = Util.constant.statistical_type.journal.id;
      var seconds = Math.ceil((parseInt(timestamp) - parseInt(comePageTime)) / 1000);
      Util.statistical(_this, type, seconds);//保存数据
    },
    destroyed: function () {
      var _this = this;
    },
    created: function () {
      var _this = this;
      _this.leadership = Utils.is_leadership();
      // 收藏夹跳转过来的
      var collection_list_str = sessionStorage.getItem('collection_list');
      if (collection_list_str && collection_list_str != '') {
        var collection_list_obj = Util.toJson(collection_list_str);
        var id = collection_list_obj.id || '';
        var type = collection_list_obj.type || '';
        sessionStorage.removeItem('collection_list');
      }
    },
    mounted () {
      var _this = this;
      _this.getData();

      _this.$nextTick(function () {
        $('.table-head').click();
      });
    },
    methods: {
      handleChange (date) {
        var _this = this;
        if (date) {
          var Datetime = Utils.dateToDate(date);
          _this.Datetime = Datetime;
          _this.from = Datetime + ' 00:00:00';
          _this.to = Datetime + ' 23:59:59';
          _this.getReviewData('Datetime');
        }
      },
      getData () {
        var _this = this;
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          page: _this.page,
          size: _this.size,
        };
        var params = {
          url: '/journal/list',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.total = res.rows;
            _this.data = _data;
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      handleSearch () {
        var _this = this;
        _this.page = 1;
        var searchConName = _this.searchConName;
      },
      changePage (page) {
        var _this = this;
        console.log('page', page);
        _this.page = page;
        _this.getData();
      },
      onRowData: function (data, index) {
        var _this = this;
        _this.show(index, data);
      },
      show: function (index, data) {
        var _this = this;
        var id = data.id;
        _this.id = id;

        var data = {
          id: _this.id,
        };
        var params = {
          url: '/journal/query',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.dataDetail = _data;
            _this.showCurrentTableData = true;
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      asyncOK: function () {
        var _this = this;
        _this.showCurrentTableData = false;
      },
      // 富文本
      initCkeditor () {
        var _this = this;
        Ckeditor.initCkeditor(_this, 'content', function (editor) {
          _this.editor = editor;
          _this.editor.setData(_this.addData.content);
        });
      },
      // 列表多选 选中数据
      selectionChange: function (selection) {
        var _this = this;
        _this.selectionArr = selection;
      },
      // 隐藏编辑页面
      hideAddModal: function () {
        var _this = this;
        var content = _this.editor ? _this.editor.getData() : '';
        if ((content == '' || content == '<p>&nbsp;</p>')) {
          _this.addCurrentTableData = false;
        } else {
          Modal.confirm(_this, {content: '取消编辑内容将丢失，请确认？'}, function () {
            _this.addCurrentTableData = false;
            if (_this.editor) {
              _this.editor.setData('');
            }
          }, function () {
          });
        }
      },
      // 显示添加界面
      add: function () {
        var _this = this;
        _this.ajaxType = 'add';
        _this.addData.content = '';
        _this.addCurrentTableData = true;
        if (!_this.editor) {
          _this.initCkeditor();
        } else {
          _this.editor.setData('');
        }
        _this.getreportUser();
      },
      // 保存数据
      save: function () {
        var _this = this;
        var content = _this.editor ? _this.editor.getData() : '';
//        var content = _this.addData.content;
        var CheckedNodes = _this.$refs.add_report_user.getCheckedNodes();
        var departments = [];
        var users = [];
        for (var k in CheckedNodes) {
          if (!CheckedNodes[k]) {
            continue;
          }
          var id = CheckedNodes[k].id;
          var type = CheckedNodes[k].type;
          if (type == 'dep') {
          } else if (type == 'user') {
            users.push(id);
          }
        }
        if (!(content && content != '')) {
          _this.$Message.error('请填写内容!');
          return false;
        }

        var data = {
          id: _this.id,
          content: content,
          report_users: users,
        };
        var url = '/journal/add';
        if (_this.ajaxType == 'update') {
          url = '/journal/update';
        }
        var params = {
          url: url,
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.page = 1;
            _this.getData();
            _this.addCurrentTableData = false;
            _this.addData.content = '';
            if (_this.editor) {
              _this.editor.setData('');
            }
          } else {
            _this.$Message.error('保存信息失败!');
          }
        }

      },
      // 显示修改界面
      update: function (data, index) {
        var _this = this;
        _this.ajaxType = 'update';
        var id = data.id;
        _this.id = id;
        var data = {
          id: _this.id,
        };
        var params = {
          url: '/journal/query',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.addData.content = _data.content;
            _this.addCurrentTableData = true;
            if (!_this.editor) {
              _this.initCkeditor();
            } else {
              _this.editor.setData(_this.addData.content);
            }
            _this.getreportUser();
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      //检阅
      review: function () {
        var _this = this;
        var end = new Date();
        var endyear = Utils.fix(end.getFullYear(), 4);
        var endmonth = Utils.fix(parseInt(end.getMonth() + 1), 2);
        _this.from = endyear + '-' + endmonth + '-01 00:00:00';
        _this.to = endyear + '-' + endmonth + '-31 23:59:59';
        _this.getReviewData('init');
        _this.DatePickerValue = Utils.dateToDate(new Date());
        _this.showReview = true;
      },
      review_back: function () {
        var _this = this;
        _this.showReview = false;
      },
      // 设置默认上报人
      reportUserFun: function () {
        var _this = this;
        _this.getreportUser();
        _this.reportUser = true;
      },
      // 查询已设置的列表
      getreportUser () {
        var _this = this;
        var data = {};
        var params = {
          url: '/user/report/list',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.checked_users_arr = _data;
          } else {
            _this.$Message.error('查询上报人失败!');
          }
          _this.getTreeData();
        }
      },
      // 获取选人 树信息
      getTreeData: function () {
        var _this = this;
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          id: 1
        };
        var params = {
          url: '/department/query',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var data = res.data || [];
            var TreeData = [];
            TreeData.push(data);
            _this.toDataFun(TreeData);
            _this.TreeData = TreeData;
          } else {
            _this.$Message.error('查询人员信息失败!');
          }
        }
      },
      // 处理树信息
      toDataFun: function (arr) {
        var _this = this;
        arr.forEach(function (e) {
          e.title = e.name;
          e.expand = true;//展开
          if (e.type) {
            e.type = 'dep';
            var checked_dep_arr = _this.checked_dep_arr;
            if (Utils.idInArray(e.id, checked_dep_arr)) {
              e.checked = true;// 选中
            }
          } else {
            e.type = 'user';
            var checked_users_arr = _this.checked_users_arr;
            if (Utils.idInArray(e.id, checked_users_arr)) {
              e.checked = true;// 选中
            }
          }
          var staff = e.staff || [];
          var children = e.children || [];
          if (children.length == 0) {
            e.children = [];
          }
          e.children.push(...staff);
          _this.toDataFun(e.children);
        });
      },
      hidereportUser: function () {
        var _this = this;
        _this.reportUser = false;
      },
      savereportUser: function () {
        var _this = this;
        var CheckedNodes = _this.$refs.report_user.getCheckedNodes();
        var departments = [];
        var users = [];
        for (var k in CheckedNodes) {
          if (!CheckedNodes[k]) {
            continue;
          }
          var id = CheckedNodes[k].id;
          var type = CheckedNodes[k].type;
          if (type == 'dep') {
          } else if (type == 'user') {
            users.push(id);
          }
        }
        var data = {
          report_users: users
        };
        var params = {
          url: '/user/report/update',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.hidereportUser();
          } else {
            _this.$Message.error('保存信息失败!');
          }
        }
      },
      handleDayChanged (data) {
        var _this = this;
        if (data.date) {
          var Datetime = Utils.dateToDate(data.date);
          _this.Datetime = Datetime;
          var ReviewData = _this.ReviewData;
          var Obj = ReviewData[Datetime] || {};
          var data = Obj.staff || [];
          _this.data_review = data;
        }
      },
      handleMonthChanged (data) {
        var _this = this;
        var Monthtime = data.replace(/年/g, '-').trim();
        Monthtime = Monthtime.replace(/月/g, '').trim();
        if (Monthtime) {
          _this.from = Monthtime + '-01 00:00:00';
          _this.to = Monthtime + '-31 23:59:59';
          _this.getReviewData();
        }
      },
      getReviewData: function (init) {
        var _this = this;
        var data = {
          from: _this.from,
          to: _this.to,
        };
        var params = {
          url: '/journal/review',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            var ReviewData = _this.ReviewData;
            for (var k in _data) {
              if (!_data[k]) {
                continue;
              }
              var time = _data[k].time;
              var staff = _data[k].staff;
              if (!ReviewData[time]) {
                ReviewData[time] = {};
              }
              ReviewData[time].time = time;
              ReviewData[time].staff = staff;
            }
            _this.ReviewData = ReviewData;
            if (init == 'init') {
              var Datetime = Utils.dateToDate(new Date());
              _this.Datetime = Datetime;
              var Obj = ReviewData[Datetime] || {};
              var data = Obj.staff || [];
              _this.data_review = data;
            } else if (init == 'Datetime') {
              var Datetime = _this.Datetime;
              var Obj = ReviewData[Datetime] || {};
              var data = Obj.staff || [];
              _this.data_review = data;
            }
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      onRowData_review: function (data, index) {
        var _this = this;
        _this.dataDetail = data;
        _this.showCurrentTableData = true;
      },
      // 删除
      remove: function () {
        var _this = this;
        var selectionArr = _this.selectionArr;
        if (selectionArr.length == 0) {
          _this.$Message.error('请填选择要删除的数据!');
          return false;
        }
        var selectionIds = [];
        for (var k in selectionArr) {
          if (!selectionArr[k]) {
            continue;
          }
          var id = selectionArr[k].id;
          selectionIds.push(id);
        }
        Modal.confirm(_this, {content: '确定删除选中的信息？'}, function () {
          var data = {
            id: selectionIds,
          };
          var params = {
            url: '/journal/deleteMultiple',
            type: Util.method.get,
            data: data,
            success: _successFun
          };
          Util.ajax(_this, params);
          function _successFun(res) {
            if (res.result == 0) {
              _this.page = 1;
              _this.getData();
            } else {
              _this.$Message.error('删除信息失败!');
            }
          }
        }, function () {
        });
      },
      // 导出
      ExportData: function () {
        var _this = this;
        var fields = [
          {
            field: 'id',
            title: '#',
            type: 'int',
            order: 1,
          },
          {
            field: 'name',
            title: '姓名',
            type: 'varchar',
            order: 2,
          },
          {
            field: 'create_time',
            title: '创建时间',
            type: 'date',
            order: 3,
          },
          {
            field: 'last_modify_time',
            title: '最后修改时间',
            type: 'date',
            order: 4,
          },
          {
            field: 'content',
            title: '内容',
            type: 'varchar',
            order: 5,
          },
        ];
        var fieldsStr = Util.toStr(fields);
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          type: 'journal',
          fields: fieldsStr,
        };
        var params = {
          url: '/file/db2excle',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var url = res.data;
            var date = Utils.dateToDateString(new Date());
            Utils.DownloadFile(url, '导出日志_' + date + '.xlsx');
          } else {
            _this.$Message.error('导出信息失败!');
          }
        }
      },
    }
  };
</script>
